#include "Bullet.hpp"

Bullet::Bullet(std::vector<String>& _Map)
	: Map(_Map)
{
	frame = 0;
	delay = 0;
	behindBullet = 'B';
}

void Bullet::nulling()
{
	Map[y][x] = behindBullet;
	frame = 0;
	x = 0;
	y = 0;
	moveX = 0;
	moveY = 0;
	rotate = 0;
	delay = 0;
	behindBullet = 'B';

	isExist = false;
}

void Bullet::Shot(int _rotate, int _x, int _y)
{
	rotate = _rotate;
	x = _x;
	y = _y;
	moveX = _x;
	moveY = _y;
	frame = 0;
	delay = 0;

	switch (rotate) {
	case 0:
		if (Map[y][moveX + 1] != 'A') {
			moveX = moveX + 1;
			isExist = true;
		}
		else {
			isExist = false;
			x = 0;
			y = 0;
			moveX = 0;
			moveY = 0;
		}
		break;
	case 1:
		if (Map[moveY + 1][x] != 'A') {
			moveY = moveY + 1;
			isExist = true;
		}
		else {
			isExist = false;
			x = 0;
			y = 0;
			moveX = 0;
			moveY = 0;
		}
		break;
	case 2:
		if (Map[y][moveX - 1] != 'A') {
			moveX = moveX - 1;
			isExist = true;
		}
		else {
			isExist = false;
			x = 0;
			y = 0;
			moveX = 0;
			moveY = 0;
		}

		break;
	case 3:
		if (Map[moveY - 1][x] != 'A') {
			moveY = moveY - 1;
			isExist = true;
		}
		else {
			isExist = false;
			x = 0;
			y = 0;
			moveX = 0;
			moveY = 0;
		}
		break;
	}

	x = moveX;
	y = moveY;
}

void Bullet::update()
{
	if (isExist) {
		frame += 0.1f;

		if (frame > 3) {
			frame -= 3;
		}

		delay += 20;

		if (delay >= 80) {

			if (moveY == 9 && (moveX == 0 || moveX == 19)) {
				moveX = (moveX == 0) ? 18 : 0;

				Map[y][x] = 'B';

				Map[moveY][moveX] = 'P';

				x = moveX;
				y = moveY;
			}

			switch (rotate) {
			case 0:
				if (Map[y][moveX + 1] != 'A') {
					moveX = moveX + 1;
				}
				else {
					Map[moveY][moveX] = behindBullet;
					behindBullet = 'B';

					isExist = false;
					x = 0;
					y = 0;
					moveX = 0;
					moveY = 0;
				}

				break;
			case 1:
				if (Map[moveY + 1][x] != 'A') {
					moveY = moveY + 1;
				}
				else {
					Map[moveY][moveX] = behindBullet;
					behindBullet = 'B';

					isExist = false;
					x = 0;
					y = 0;
					moveX = 0;
					moveY = 0;
				}

				break;
			case 2:
				if (Map[y][moveX - 1] != 'A') {
					moveX = moveX - 1;
				}
				else {
					Map[moveY][moveX] = behindBullet;
					behindBullet = 'B';

					isExist = false;
					x = 0;
					y = 0;
					moveX = 0;
					moveY = 0;
				}


				break;
			case 3:
				if (Map[moveY - 1][x] != 'A') {
					moveY = moveY - 1;
				}
				else {
					Map[moveY][moveX] = behindBullet;
					behindBullet = 'B';

					isExist = false;
					x = 0;
					y = 0;
					moveX = 0;
					moveY = 0;
				}

				break;
			}

			if (isExist) {
				if (Map[moveY][moveX] == ' ' || Map[moveY][moveX] == 'B' || Map[moveY][moveX] == 'X' ||
					Map[moveY][moveX] == 'R' || Map[moveY][moveX] == 'V'
					) {
					Map[y][x] = behindBullet;
					behindBullet = (char)Map[moveY][moveX];

					Map[moveY][moveX] = 'P';

					x = moveX;
					y = moveY;
				}
			}
			delay = 0;
		}
	}
}